home *** CD-ROM | disk | FTP | other *** search
/ C & C++ Multimedia Cyber Classroom / C and C++ Multimedia Cyber Classroom (Prentice Hall) (1998).iso / src / fig15_12.jar / Ch15 / Fig15_12 / STACK / STACK.H < prev    next >
C/C++ Source or Header  |  1997-08-26  |  2KB  |  85 lines

  1. // STACK.H
  2. // Definition of class Stack
  3. #ifndef STACK_H
  4. #define STACK_H
  5.  
  6. #include <iostream.h>
  7. #include <assert.h>
  8. #include "stacknd.h"
  9.  
  10. template <class T>
  11. class Stack {
  12. public:
  13.    Stack();              // default constructor
  14.    ~Stack();             // destructor
  15.    void push( T & );     // insert item in stack
  16.    T pop();              // remove item from stack
  17.    int isEmpty() const;  // is the stack empty?
  18.    void print() const;   // output the stack
  19. private:
  20.    StackNode<T> *topPtr;    // pointer to fist StackNode
  21. };
  22.  
  23. // Member function definitions for class Stack
  24. template <class T>
  25. Stack<T>::Stack() { topPtr = 0; }
  26.  
  27. template <class T>
  28. Stack<T>::~Stack()
  29. {
  30.    StackNode<T> *tempPtr, *currentPtr = topPtr;
  31.  
  32.    while ( currentPtr != 0 ) {
  33.       tempPtr = currentPtr;
  34.       currentPtr = currentPtr->nextPtr;
  35.       delete tempPtr;
  36.    }
  37. }
  38.  
  39. template <class T>
  40. void Stack<T>::push( T &d )
  41. {
  42.    StackNode<T> *newPtr = new StackNode<T>( d, topPtr );
  43.  
  44.    assert( newPtr != 0 );  // was memory allocated?
  45.    topPtr = newPtr;
  46. }
  47.  
  48. template <class T>
  49. T Stack<T>::pop()
  50. {
  51.    assert( !isEmpty() );
  52.  
  53.    StackNode<T> *tempPtr = topPtr;
  54.  
  55.    topPtr = topPtr->nextPtr;
  56.    T poppedValue = tempPtr->data;
  57.    delete tempPtr;
  58.    return poppedValue;
  59. }
  60.  
  61. template <class T>
  62. int Stack<T>::isEmpty() const { return topPtr == 0; }
  63.  
  64. template <class T>
  65. void Stack<T>::print() const
  66. {
  67.    StackNode<T> *currentPtr = topPtr;
  68.  
  69.    if ( isEmpty() )          // Stack is empty
  70.       cout << "Stack is empty" << endl;
  71.    else {                    // Stack is not empty
  72.       cout << "The stack is:" << endl;
  73.  
  74.       while ( currentPtr != 0 ) {
  75.          cout << currentPtr->data << ' ';
  76.          currentPtr = currentPtr->nextPtr;
  77.       }
  78.  
  79.       cout << endl;
  80.    }
  81. }
  82.  
  83. #endif
  84.  
  85.